import OpenAI from 'openai';
import logger from "../utils/log";

const gptApi = async (promptGPT: string, model: string, key: string, baseUrl: string = '') => {
    try {
        // 参数验证
        if (!promptGPT) {
            throw new Error('提示文本不能为空');
        }
        if (!model) {
            throw new Error('模型名称不能为空');
        }
        if (!key) {
            throw new Error('OpenAI Key不能为空，请在设置页面配置');
        }
        
        logger.info(`promptGPT: ${promptGPT}`);
        const options: any = {
            apiKey: key,
        };
        
        // 如果提供了baseUrl，添加到配置中
        if (baseUrl) {
            options.baseURL = baseUrl;
            logger.info(`使用自定义baseURL: ${baseUrl}`);
        }
        
        const openai = new OpenAI(options);
        logger.info(`model: ${model}`);
        
        const chatCompletion = await openai.chat.completions.create({
            messages: [{ role: 'user', content: promptGPT }],
            model: model,
        });
        
        if (!chatCompletion || !chatCompletion.choices || chatCompletion.choices.length === 0) {
            throw new Error('OpenAI API返回结果无效');
        }
        
        logger.info(`chatCompletion: ${JSON.stringify(chatCompletion)}`);
        return chatCompletion.choices[0].message.content;
    } catch (error: any) {
        logger.error(`GPT API错误: ${error.message}`);
        // 重新抛出错误，让调用方处理
        throw error;
    }
}

export { gptApi };